package handler

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"nov6-test/cache"
	"nov6-test/models"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	var good []models.Good
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	name := c.Query("name")
	offset := (page - 1) * size
	redis_key := fmt.Sprintf("good_list_") + strconv.Itoa(page)
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		if name == "" {
			models.DB.Offset(offset).Limit(size).Find(&good)
		} else {
			models.DB.Where("name LIKE ?", "%"+name+"%").
				Offset(offset).Limit(size).Find(&good)
		}
		jsonData, _ := json.Marshal(good)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &good)
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "列表获取成功",
		"data": good,
	})
	return
}

func CommentAdd(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	content := c.PostForm("content")
	data := models.Comment{
		Uid:     uid,
		Content: content,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "评论失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "评论成功",
	})
	return
}

func CommentList(c *gin.Context) {
	var comment []models.Comment
	redis_key := "comment_list"
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		models.DB.Find(&comment)
		jsonData, _ := json.Marshal(comment)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &comment)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "评论列表获取成功",
		"data": comment,
	})
	return
}
